// HTTP 状态码参考工具渲染器
window.HttpStatusRenderer = class HttpStatusRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="globe" class="w-8 h-8 inline mr-3 text-blue-600"></i>
                HTTP 状态码参考
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">快速查询HTTP状态码的含义和用法，支持搜索和分类浏览。</p>
            </div>
            
            <!-- 搜索区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="search" class="w-5 h-5 inline mr-2"></i>
                    快速查询
                </h3>
                <div class="flex flex-col sm:flex-row gap-3">
                    <div class="flex-1">
                        <input 
                            id="status-search" 
                            type="text" 
                            placeholder="输入状态码或描述关键词（如：404, Not Found, 未找到）" 
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        >
                    </div>
                    <button 
                        id="clear-search" 
                        class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition duration-200 flex items-center justify-center"
                    >
                        <i data-feather="x" class="w-4 h-4"></i>
                        <span class="ml-2 hidden sm:inline">清空</span>
                    </button>
                </div>
                
                <!-- 搜索结果 -->
                <div id="search-results" class="mt-4 hidden">
                    <h4 class="text-md font-medium text-gray-800 mb-3">搜索结果</h4>
                    <div id="search-results-content"></div>
                </div>
            </div>

            <!-- 状态码分类展示 -->
            <div id="status-categories">
                <!-- 动态生成的分类内容 -->
            </div>

            <!-- 单个状态码详情模态框 -->
            <div id="status-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
                <div class="flex items-center justify-center min-h-screen p-4">
                    <div class="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-bold text-gray-800">状态码详情</h3>
                            <button id="close-modal" class="text-gray-400 hover:text-gray-600">
                                <i data-feather="x" class="w-6 h-6"></i>
                            </button>
                        </div>
                        <div id="modal-content">
                            <!-- 动态内容 -->
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        const searchInput = document.getElementById('status-search');
        const clearSearchBtn = document.getElementById('clear-search');
        const searchResults = document.getElementById('search-results');
        const searchResultsContent = document.getElementById('search-results-content');
        const statusCategories = document.getElementById('status-categories');
        const statusModal = document.getElementById('status-modal');
        const closeModalBtn = document.getElementById('close-modal');
        const modalContent = document.getElementById('modal-content');

        // 初始化显示所有状态码
        this.displayAllCategories();

        // 搜索功能
        searchInput.addEventListener('input', DevToolsUtils.debounce((e) => {
            const query = e.target.value.trim();
            if (query === '') {
                searchResults.classList.add('hidden');
                statusCategories.classList.remove('hidden');
                return;
            }

            const result = HttpStatusTool.searchStatus(query);
            if (result.success) {
                this.displaySearchResults(result.data);
            }
        }, 300));

        // 清空搜索
        clearSearchBtn.addEventListener('click', () => {
            searchInput.value = '';
            searchResults.classList.add('hidden');
            statusCategories.classList.remove('hidden');
        });

        // 模态框关闭
        closeModalBtn.addEventListener('click', () => {
            statusModal.classList.add('hidden');
        });

        statusModal.addEventListener('click', (e) => {
            if (e.target === statusModal) {
                statusModal.classList.add('hidden');
            }
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !statusModal.classList.contains('hidden')) {
                statusModal.classList.add('hidden');
            }
        });

        // 初始化 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }

    static displayAllCategories() {
        const result = HttpStatusTool.getAllStatusCodes();
        if (!result.success) {
            DevToolsUtils.showToast(result.error, 'error');
            return;
        }

        const statusCategories = document.getElementById('status-categories');
        let html = '';

        for (const [categoryName, codes] of Object.entries(result.data)) {
            if (codes.length === 0) continue;

            const categoryColor = this.getCategoryColor(categoryName);
            html += `
                <div class="bg-white rounded-xl shadow-sm border mb-6">
                    <div class="p-6 border-b border-gray-100">
                        <h3 class="text-xl font-semibold ${categoryColor} flex items-center">
                            <i data-feather="${this.getCategoryIcon(categoryName)}" class="w-5 h-5 mr-2"></i>
                            ${categoryName}
                        </h3>
                    </div>
                    <div class="p-6">
                        <div class="grid gap-3">
                            ${codes.map(code => `
                                <div class="status-code-item flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition duration-200"
                                     data-code="${code.code}">
                                    <div class="flex items-center space-x-3">
                                        <span class="font-mono text-lg font-bold ${this.getCodeColor(code.code)}">${code.code}</span>
                                        <span class="font-medium text-gray-800">${code.message}</span>
                                    </div>
                                    <i data-feather="info" class="w-4 h-4 text-gray-400"></i>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;
        }

        statusCategories.innerHTML = html;

        // 为每个状态码项目添加点击事件
        document.querySelectorAll('.status-code-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const code = e.currentTarget.getAttribute('data-code');
                this.showStatusDetail(code);
            });
        });

        // 更新 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static displaySearchResults(results) {
        const searchResults = document.getElementById('search-results');
        const searchResultsContent = document.getElementById('search-results-content');
        const statusCategories = document.getElementById('status-categories');

        if (results.length === 0) {
            searchResultsContent.innerHTML = `
                <div class="text-center py-8 text-gray-500">
                    <i data-feather="search" class="w-12 h-12 mx-auto mb-2 text-gray-300"></i>
                    <p>未找到匹配的状态码</p>
                </div>
            `;
        } else {
            searchResultsContent.innerHTML = `
                <div class="grid gap-3">
                    ${results.map(code => `
                        <div class="status-code-item flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition duration-200"
                             data-code="${code.code}">
                            <div class="flex items-center space-x-3">
                                <span class="font-mono text-lg font-bold ${this.getCodeColor(code.code)}">${code.code}</span>
                                <div>
                                    <div class="font-medium text-gray-800">${code.message}</div>
                                    <div class="text-sm text-gray-500">${code.category}</div>
                                </div>
                            </div>
                            <i data-feather="info" class="w-4 h-4 text-gray-400"></i>
                        </div>
                    `).join('')}
                </div>
            `;

            // 为搜索结果添加点击事件
            document.querySelectorAll('#search-results-content .status-code-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    const code = e.currentTarget.getAttribute('data-code');
                    this.showStatusDetail(code);
                });
            });
        }

        searchResults.classList.remove('hidden');
        statusCategories.classList.add('hidden');

        // 更新 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static showStatusDetail(code) {
        const result = HttpStatusTool.getStatusInfo(code);
        if (!result.success) {
            DevToolsUtils.showToast(result.error, 'error');
            return;
        }

        const { data } = result;
        const modalContent = document.getElementById('modal-content');
        const statusModal = document.getElementById('status-modal');

        modalContent.innerHTML = `
            <div class="text-center mb-6">
                <div class="inline-block px-4 py-2 rounded-full ${this.getCodeBgColor(data.code)} mb-3">
                    <span class="font-mono text-2xl font-bold ${this.getCodeColor(data.code)}">${data.code}</span>
                </div>
                <h4 class="text-xl font-bold text-gray-800">${data.message}</h4>
                <p class="text-sm text-gray-500 mt-1">${data.category}</p>
            </div>
            
            <div class="bg-gray-50 rounded-lg p-4 mb-4">
                <h5 class="font-medium text-gray-800 mb-2">详细说明</h5>
                <p class="text-gray-600 leading-relaxed">${data.description}</p>
            </div>
            
            <div class="flex justify-center space-x-3">
                <button id="copy-code" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition duration-200 flex items-center">
                    <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                    复制状态码
                </button>
                <button id="copy-message" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition duration-200 flex items-center">
                    <i data-feather="type" class="w-4 h-4 mr-2"></i>
                    复制描述
                </button>
            </div>
        `;

        // 添加复制功能
        document.getElementById('copy-code').addEventListener('click', () => {
            DevToolsUtils.copyToClipboard(data.code.toString());
            DevToolsUtils.showToast('状态码已复制', 'success');
        });

        document.getElementById('copy-message').addEventListener('click', () => {
            DevToolsUtils.copyToClipboard(`${data.code} ${data.message}`);
            DevToolsUtils.showToast('状态码和描述已复制', 'success');
        });

        statusModal.classList.remove('hidden');

        // 更新 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static getCategoryColor(categoryName) {
        if (categoryName.includes('1xx')) return 'text-blue-600';
        if (categoryName.includes('2xx')) return 'text-green-600';
        if (categoryName.includes('3xx')) return 'text-yellow-600';
        if (categoryName.includes('4xx')) return 'text-red-600';
        if (categoryName.includes('5xx')) return 'text-purple-600';
        return 'text-gray-600';
    }

    static getCategoryIcon(categoryName) {
        if (categoryName.includes('1xx')) return 'info';
        if (categoryName.includes('2xx')) return 'check-circle';
        if (categoryName.includes('3xx')) return 'arrow-right';
        if (categoryName.includes('4xx')) return 'alert-circle';
        if (categoryName.includes('5xx')) return 'x-circle';
        return 'help-circle';
    }

    static getCodeColor(code) {
        if (code >= 100 && code < 200) return 'text-blue-600';
        if (code >= 200 && code < 300) return 'text-green-600';
        if (code >= 300 && code < 400) return 'text-yellow-600';
        if (code >= 400 && code < 500) return 'text-red-600';
        if (code >= 500 && code < 600) return 'text-purple-600';
        return 'text-gray-600';
    }

    static getCodeBgColor(code) {
        if (code >= 100 && code < 200) return 'bg-blue-100';
        if (code >= 200 && code < 300) return 'bg-green-100';
        if (code >= 300 && code < 400) return 'bg-yellow-100';
        if (code >= 400 && code < 500) return 'bg-red-100';
        if (code >= 500 && code < 600) return 'bg-purple-100';
        return 'bg-gray-100';
    }
};